﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Dcms.Common;
using Dcms.Config;
using Dcms.BLL;
using Dcms.Model;

public partial class Manage_Modle_System_EditWebSiteInfo : System.Web.UI.Page
{
    public CompetenceLib CL = new CompetenceLib();
    public String ROLESTR = "WEBSITEINFO";
    private readonly string strUploadPathRoot = "/UserFiles";
    private readonly string strUploadImageType = ",.jpg,.jpeg,.gif,.bmp,.png,";

    /// <summary>
    /// 页面加载
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        CL.IsLogin();
        if (!IsPostBack)
        {
            BindData();
        }
    }

    /// <summary>
    /// 初使化数据
    /// </summary>
    private void BindData()
    {
        WebSiteConfigInfo etWebSiteConfigInfo = WebSiteConfigs.Deserialize("~/SystemConfig/WebSiteInfo.config");
        txtSiteName.Text = etWebSiteConfigInfo.SiteName;
        txtKeyword.Text = etWebSiteConfigInfo.Keyword;
        txtDescription.Text = etWebSiteConfigInfo.Description;
        txtIcpNo.Text = etWebSiteConfigInfo.IcpNo;
        txtAddress.Text = etWebSiteConfigInfo.Address;
        txtTel.Text = etWebSiteConfigInfo.Tel;
        txtFax.Text = etWebSiteConfigInfo.Fax;
        txtContacter.Text = etWebSiteConfigInfo.Contacter;
        txtQQ.Text = etWebSiteConfigInfo.QQ;
        txtMSN.Text = etWebSiteConfigInfo.MSN;
        txtSkype.Text = etWebSiteConfigInfo.Skype;
        txtTaobao.Text = etWebSiteConfigInfo.Taobao;
        //fckStatCode.Value = etWebSiteConfigInfo.StatCode;
        txtStatCode.Text = etWebSiteConfigInfo.StatCode;
        txtsmtpServer.Text = etWebSiteConfigInfo.smtpServer;
        txtmailUserName.Text = etWebSiteConfigInfo.mailUserName;
        txtmailPassWord.Text = etWebSiteConfigInfo.mailPassWord;

        this.ddl_defaultStyle.DataSource = GetAllTemplateList();
        this.ddl_defaultStyle.DataTextField = "styleName";
        this.ddl_defaultStyle.DataValueField = "styleName";
        this.ddl_defaultStyle.DataBind();
        ddl_defaultStyle.SelectedValue = etWebSiteConfigInfo.defaultStyle;
    }



    #region 上传图片


    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="filName"></param>
    /// <param name="strFileName"></param>
    /// <param name="strMsg"></param>
    /// <returns></returns>
    private bool UpLoadFile(string strDirectoryName, string filName, ref string strFileName, out string strMsg)
    {
        bool bRef = false;
        strMsg = "";
        string strOldFileName = strFileName;
        try
        {
            String Pakeage = DateTime.Now.ToString("yyyy-MM-dd");

            //实例文件读取方法，对传入客户端的文件进行解析
            System.Web.HttpFileCollection Files = System.Web.HttpContext.Current.Request.Files;
            HttpPostedFile file = Files[filName];
            if (file != null)
            {
                //解析所得文件名
                String FileName = System.IO.Path.GetFileName(file.FileName);
                String ExtensionName = System.IO.Path.GetExtension(file.FileName);
                if (CheckImageType(ExtensionName))
                {
                    //解析所得路径
                    FileName = System.Guid.NewGuid().ToString();
                    strFileName = strUploadPathRoot + "/" + strDirectoryName + "/" + Pakeage + "/" + FileName + ExtensionName;
                    if (File.Exists(Server.MapPath(strFileName)))
                    {
                        strFileName = strUploadPathRoot + "/" + strDirectoryName + "/" + Pakeage + "/" + FileName + "_1" + ExtensionName;
                    }
                    string strPath = Server.MapPath(strFileName);
                    if (CheckDirectory(strPath))
                    {
                        file.SaveAs(strPath);
                        //上传完成,删除旧图片
                        try
                        {
                            if (strOldFileName != null && strOldFileName != "")
                            {
                                File.Delete(Server.MapPath(strOldFileName));
                            }
                        }
                        catch
                        { }
                        return true;
                    }
                    else
                    {
                        strMsg = "创建文件夹失败，请检查是否有读写权限！";
                    }
                }
                else
                {
                    strMsg = "您上传的文件类型不正确，请重新上传！";
                }
            }
        }
        catch (Exception ex)
        {
            strMsg = ex.Message;
        }
        return bRef;
    }

    /// <summary>
    /// 判断是否有上传工具
    /// </summary>
    /// <param name="filName"></param>
    /// <returns></returns>
    private bool CheckUploadTool(string filName)
    {
        bool bRef = false;
        try
        {
            System.Web.HttpFileCollection Files = System.Web.HttpContext.Current.Request.Files;
            HttpPostedFile file = Files.Get(filName);
            if (file != null && file.FileName != "")
            {
                return true;
            }
        }
        catch
        { }
        return bRef;
    }

    private bool CheckImageType(string ExtensionName)
    {
        bool bRef = false;
        try
        {
            return strUploadImageType.ToLower().Contains("," + ExtensionName.ToLower() + ",");
        }
        catch
        { }
        return bRef;
    }

    /// <summary>
    /// 判断文件是否存在,不存在则判断文件
    /// </summary>
    /// <param name="strPath"></param>
    /// <returns></returns>
    private bool CheckDirectory(string strPath)
    {
        bool bRef = false;
        try
        {
            if (!Directory.Exists(Path.GetDirectoryName(strPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(strPath));
                bRef = true;
            }
            else
            {
                bRef = true;
            }
        }
        catch
        {
        }
        return bRef;
    }

    private bool CheckUpload(string strDirectoryName, string filName, ref string strFileName, out string strMsg)
    {
        if (CheckUploadTool(filName))
        {
            if (UpLoadFile(strDirectoryName, filName, ref strFileName, out strMsg) == false)
            {
                RegisterStartupScript(this.ToString(), string.Format("<script language='javascript'>alert('{0}');</script>", strMsg));
                return false;
            }
            return true;
        }
        else
        {
            strMsg = "";
            return false;
        }
    }
    #endregion



    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        WebSiteConfigInfo etWebSiteConfigInfo = WebSiteConfigs.Deserialize("~/SystemConfig/WebSiteInfo.config");
        etWebSiteConfigInfo.SiteName = txtSiteName.Text.Trim();
        etWebSiteConfigInfo.Keyword = txtKeyword.Text.Trim();
        etWebSiteConfigInfo.Description = txtDescription.Text.Trim();
        etWebSiteConfigInfo.IcpNo = txtIcpNo.Text.Trim();
        etWebSiteConfigInfo.Address = txtAddress.Text.Trim();
        etWebSiteConfigInfo.Tel = txtTel.Text.Trim();
        etWebSiteConfigInfo.Fax = txtFax.Text.Trim();
        etWebSiteConfigInfo.Contacter = txtContacter.Text.Trim();
        etWebSiteConfigInfo.QQ = txtQQ.Text.Trim();
        etWebSiteConfigInfo.MSN = txtMSN.Text.Trim();
        etWebSiteConfigInfo.Skype = txtSkype.Text.Trim();
        etWebSiteConfigInfo.Taobao = txtTaobao.Text.Trim();
       // etWebSiteConfigInfo.StatCode = fckStatCode.Value.Trim();
        etWebSiteConfigInfo.StatCode = txtStatCode.Text;
        etWebSiteConfigInfo.smtpServer = txtsmtpServer.Text.Trim();
        etWebSiteConfigInfo.mailUserName = txtmailUserName.Text.Trim();
        etWebSiteConfigInfo.mailPassWord = txtmailPassWord.Text.Trim();
        etWebSiteConfigInfo.defaultStyle = ddl_defaultStyle.SelectedValue.Trim();

        //保存图片
        string strDirectoryName = "SiteInfo";

        string strMsg = "";
        #region 处理上传图片
        string strImage = etWebSiteConfigInfo.IcpImage;

        bool bImageUploadType = CheckUpload(strDirectoryName, "fldIcpImage", ref strImage, out strMsg);
        if (bImageUploadType == false && strMsg != "")
        {
            RegisterStartupScript(this.ToString(), string.Format("<script language='javascript'>alert('{0}');</script>", strMsg));
            return;
        }
        if (bImageUploadType == true)
        {
            etWebSiteConfigInfo.IcpImage = strImage;
        }
        #endregion
        
        StringBuilder xmlContent = new StringBuilder();
        xmlContent.Append("<?xml version=\"1.0\" standalone=\"yes\"?>\n<urls>");
        DataTable dt = GetAllTemplateList();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["styleName"].ToString().Trim() == ddl_defaultStyle.SelectedValue.Trim())
            {
                xmlContent.Append("\n<rewrite name=\"" + dt.Rows[i]["styleName"] + "\" path=\"/\" value=\"-1\"  page=\"" + dt.Rows[i]["stylePage"] + "\" />");
            }
            else
            {
                xmlContent.Append("\n<rewrite name=\"" + dt.Rows[i]["styleName"] + "\" path=\"" + dt.Rows[i]["styleName"] + "/\" value=\"0\"  page=\"" + dt.Rows[i]["stylePage"] + "\" />");
            }
        }
        xmlContent.Append("\n</urls>");

        if (WebSiteConfigs.Serialiaze(etWebSiteConfigInfo, "~/SystemConfig/WebSiteInfo.config") && saveXml(xmlContent.ToString()))
        {
            RegisterStartupScript(this.ToString(), "<script>alert('保存成功!');</script>");
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected DataTable GetAllTemplateList()
    {
        DirectoryInfo dirinfo = new DirectoryInfo(Utils.GetMapPath(ConfigurationManager.AppSettings["TempLatePath"]));
        DataTable dt = new DataTable();
        dt.Columns.Add("styleName", typeof(string));
        dt.Columns.Add("stylePage", typeof(string));
        foreach (DirectoryInfo dir in dirinfo.GetDirectories())
        {
            DataRow dr = dt.NewRow();
            dr["styleName"] = dir.Name;
            dr["stylePage"] = "aspx/" + dir.Name + "/";
            dt.Rows.Add(dr);
        }
        return dt;
    }

    /// <summary>
    /// 生成url.config
    /// </summary>
    /// <param name="xmlContent"></param>
    /// <param name="WebPath"></param>
    /// <returns></returns>
    protected bool saveXml(string xmlContent)
    {
        try
        {
            StreamWriter sw = new StreamWriter(Server.MapPath("~/SystemConfig/url.config"), false, System.Text.Encoding.UTF8);
            sw.Write(xmlContent);
            sw.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }
}